###### Makefile ######

######################################
# target
######################################
TARGET=lm
PDCURSES_DIR=ui/pdcurses
######################################
# building variables
######################################
# debug build?
DEBUG = 1
# optimization
OPT = -O2 -flto -std=c99

# Build path
SRC    := ui

######################################
# source
######################################
# C sources
C_SOURCES =  \
$(wildcard parser/*.c)  \
$(wildcard common/*.c)  \
$(wildcard $(SRC)/*.cpp)  \
$(wildcard $(SRC)/*.c)    \

# C defines
C_DEFS = \
-D
# AS includes
AS_INCLUDES = 

# C includes
C_INCLUDES =           \
-I.                    \
-I$(PDCURSES_DIR)      \
-I$(PDCURSES_DIR)/common         \
-I$(PDCURSES_DIR)/Ipdcurses    \
-I$(PDCURSES_DIR)/wincon    \
-I$(SRC)   

BUILD_DIR    := build
#######################################
# Compiler Setting
#######################################
PREFIX =
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc 
CP = $(PREFIX)objcopy
AR = $(PREFIX)ar
SZ = $(PREFIX)size
OD = $(PREFIX)objdump
HEX =$(CP) -O ihex
BIN =$(CP) -O binary -S

PDCURSES_LIB=pdcurses.a
PDCURSES_LIB_SRC=$(PDCURSES_DIR)/wincon

LIB_DIR = -L$(PDCURSES_DIR)/wincon

LIB_OPT = -lmingw32 -lgdi32 -l:$(PDCURSES_LIB)

CFLAGS := -Wall  $(C_INCLUDES)  

ifeq ($(DEBUG), 1)
CFLAGS += -g -gdwarf-2 -DLM_CONFIG_DEBUG=1 -DLM_CONFIG_LOG_LEVEL=0
endif

# libraries
#LIBS = -lc_nano -lm
LDFLAGS = $(OPT)   $(LIB_DIR) $(LIB_OPT) $(LIBS)

# default action: build all
all: $(TARGET).exe

#######################################
# build the application
#######################################
# list of objects
OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))

$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR)
	@echo "CC $<"
	@$(CC) -c $(CFLAGS) -MMD -MP \
		-MF  $(BUILD_DIR)/$(notdir $(<:.c=.d)) \
		-Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@

$(TARGET).exe: $(PDCURSES_LIB) $(OBJECTS)  Makefile
	@echo "LD $@"
	@$(CC) $(OBJECTS) $(LDFLAGS) -o $@
	@strip $@
	@echo "SIZE $@"
	@$(SZ) $@


$(PDCURSES_LIB): $(PDCURSES_LIB_SRC)
	@echo "CC libpdcurses"
	@make -C $(PDCURSES_LIB_SRC)

$(BUILD_DIR):
	mkdir $@

#######################################
# clean up
#######################################

clean:
	-rm -fR $(BUILD_DIR) $(TARGET).exe $(PDCURSES_LIB_SRC)/*.o $(PDCURSES_LIB_SRC)/*.a

rebuild:
	-rm -fR $(BUILD_DIR) $(TARGET).exe 
	make
